import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class KeyBoardBean {
  ///移动
  double x = 0; //水平方向移动，（负数向左，正数向右）
  double y = 0; //垂直方向移动，（负数向上，正数向下）
  ///旋转
  double r = 0;

  ///是否聚焦,首次创建的时候，默认是聚焦的。
  bool isFocuse = true;

  //组件
  PositionComponent? positionComponent = null;

  //是否清除
  bool isClear = false;
}

//获取按键监听
/// var _value = HardwareKeyboardManage.getListener(_key);
class HardwareKeyboardManage {
  ///按键监听
  static HardwareKeyboard? _hardwareKeyboard;

  //清除按键
  static PhysicalKeyboardKey _key_clear = PhysicalKeyboardKey.keyC;

  ///移动
  static double _x = 0; //水平方向移动，（负数向左，正数向右）
  static double _y = 0; //垂直方向移动，（负数向上，正数向下）
  static double _speed = 0.5; //移动速度
  static PhysicalKeyboardKey _key_left = PhysicalKeyboardKey.keyA; //左方向键
  static bool _iskey_left_down = false; //判断左方向键，是否按下。
  static PhysicalKeyboardKey _key_right = PhysicalKeyboardKey.keyD; //右方向键
  static bool _iskey_right_down = false; //判断右方向键，是否按下。
  static PhysicalKeyboardKey _key_up = PhysicalKeyboardKey.keyW; //上方向键
  static bool _iskey_up_down = false; //判断上方向键，是否按下。
  static PhysicalKeyboardKey _key_down = PhysicalKeyboardKey.keyS; //下方向键
  static bool _iskey_down_down = false; //判断下方向键，是否按下。
  ///旋转
  static double _r = 0;
  static double _angle = 3.14; //旋转角度
  static PhysicalKeyboardKey _rotate_left = PhysicalKeyboardKey.keyQ; //左旋转键
  static bool _isrotate_left = false; //判断是否左旋转
  static PhysicalKeyboardKey _rotate_right = PhysicalKeyboardKey.keyE; //右旋转键
  static bool _isrotate_right = false; //判断是否右旋转

  static Map<String?, KeyBoardBean> _map = Map();

  ///获取按键监听结果
  ///每一个key对应一个KeyBoardBean
  static KeyBoardBean getListener(String key) {
    var _key = _map[key];
    if (_key == null) {
      _key = KeyBoardBean();
      _map[key] = _key;
      _addListener(key);
    }
    return _key;
  }

  ///获取所有的按键监听集合
  static Map<String?, KeyBoardBean> getAllListener() {
    return _map;
  }

  ///清除指定按键监听
  static removeListener(String key) {
    _map?.remove(key);
  }

  ///清除所有监听
  static clearListener(String key) {
    _map?.clear();
  }

  static _addListener(String key) {
    if (_map[key] == null) {
      _map[key] = KeyBoardBean();
    }
    if (_hardwareKeyboard == null) {
      //加上这行，防止应用初始化未完成，导致按键监听异常
      WidgetsFlutterBinding.ensureInitialized();
      _hardwareKeyboard = HardwareKeyboard.instance;
      KeyEventCallback handler = (event) {
        try {
          ///fixme 亲测，能监听键盘按键，无法监听鼠标。
          // runtimeType:KeyDownEvent	physicalKey:PhysicalKeyboardKey#83d36(usbHidUsage: "0x00070007", debugName: "Key D")
          // runtimeType:KeyRepeatEvent	physicalKey:PhysicalKeyboardKey#83d36(usbHidUsage: "0x00070007", debugName: "Key D")
          // runtimeType:KeyRepeatEvent	physicalKey:PhysicalKeyboardKey#83d36(usbHidUsage: "0x00070007", debugName: "Key D")
          // runtimeType:KeyUpEvent	physicalKey:PhysicalKeyboardKey#83d36(usbHidUsage: "0x00070007", debugName: "Key D")
          // print("=====================runtimeType:${event.runtimeType}\tphysicalKey:${event.physicalKey}");
          if (event.runtimeType == KeyDownEvent) {
            //按键按下
            ///移动
            if (event.physicalKey == _key_up) {
              //向上移动
              _y = -_speed;
              _iskey_up_down = true;
            } else if (event.physicalKey == _key_down) {
              //向下移动
              _y = _speed;
              _iskey_down_down = true;
            } else if (event.physicalKey == _key_left) {
              //向左移动
              _x = -_speed;
              _iskey_left_down = true;
            } else if (event.physicalKey == _key_right) {
              //向右移动
              _x = _speed;
              _iskey_right_down = true;
            }

            ///旋转
            if (event.physicalKey == _rotate_left) {
              _r = -_angle;
              _isrotate_left = true;
            } else if (event.physicalKey == _rotate_right) {
              _r = _angle;
              _isrotate_right = true;
            }
          } else if (event.runtimeType == KeyUpEvent) {
            //按键离开
            ///移动
            if (event.physicalKey == _key_up) {
              _y = 0;
              _iskey_up_down = false;
              if (_iskey_down_down) {
                _y = _speed; //向下移动
              }
            } else if (event.physicalKey == _key_down) {
              _y = 0;
              _iskey_down_down = false;
              if (_iskey_up_down) {
                _y = -_speed; //向上移动
              }
            } else if (event.physicalKey == _key_left) {
              _x = 0;
              _iskey_left_down = false;
              if (_iskey_right_down) {
                _x = _speed; //向右移动
              }
            } else if (event.physicalKey == _key_right) {
              _x = 0;
              _iskey_right_down = false;
              if (_iskey_left_down) {
                _x = -_speed; //向左移动
              }
            }

            ///旋转
            if (event.physicalKey == _rotate_left) {
              _r = 0;
              _isrotate_left = false;
              if (_isrotate_right) {
                _r = _angle; //右旋转
              }
            } else if (event.physicalKey == _rotate_right) {
              _r = 0;
              _isrotate_right = false;
              if (_isrotate_left) {
                _r = -_angle; //左旋转
              }
            }
          }

          ///清除
          var isClear = false;
          if (event.physicalKey == _key_clear) {
            isClear = true;
          }

          ///按键监听赋值
          _map.forEach((key, value) {
            if (value.isFocuse) {
              value.x = _x;
              value.y = _y;
              value.r = _r;
              value.isClear = isClear;
            } else {
              value.x = 0;
              value.y = 0;
              value.r = 0;
              value.isClear = false;
            }
          });
          // return true;
          return false; //这里对按键不作拦截处理，我们只是监听。
        } catch (e) {
          print("按键异常：${e}");
        }
        return false;
      };
      try {
        _hardwareKeyboard?.addHandler(handler);
      } catch (e, s) {
        print("按键事件添加异常：${e}");
      }
    }
  }
}
